<script setup lang="ts">
import { ref, nextTick } from 'vue'
import axios from 'axios'

const messages = ref<{ sender: 'user' | 'bot', content: string, type?: string }[]>([])
const userInput = ref('')
// 1-生成文本 2-生成图片
const sendMessageType = ref('1')
const queryImage = async (userMessage: string) => {
  messages.value.push({ sender: 'bot', content: '', type: 'image' });
  const app = await axios.get(`/api/ai/queryImage?message=${encodeURIComponent(userMessage)}`)
  console.log('app', app)
  messages.value[messages.value.length - 1].content = app?.data?.data?.images || ''
}
let evtSource: EventSource | null = null

const fetchData = async (userMessage: string) => {
  try {
    messages.value.push({ sender: 'bot', content: '' });
    console.log('Sending message:', userMessage)
    evtSource = new EventSource(`/api/ai/queryMessage?message=${encodeURIComponent(userMessage)}`);
    evtSource.onmessage = (event) => {
      const data = JSON.parse(event.data);
      if (data.done) {
        evtSource && evtSource.close();
        return
      }
      const messageItem = messages.value[messages.value.length - 1];
      messageItem.content += data.response.replace(/<think>/, '<p>已深度思考</p><p class="message_response">').replace(/<\/think>/, '</p>')
      messageItem.content = messageItem.content.replace(/<p class=\"message_response\">\n/, '<p class="message_response">')
      messageItem.content = messageItem.content.replace(/.*<p class=\"message_response\"><\/p>\n\n/, '')
      // 确保内容更新后滚动到底部
      nextTick(() => {
        const chatContainer = document.querySelector('.chat-container');
        if (chatContainer) {
          chatContainer.scrollTop = chatContainer.scrollHeight;
        }
      });
    };
  } catch (error) {
    console.error('Error fetching data:', error);
  }
};

const sendMessage = () => {
  if (userInput.value.trim() === '') return;
  messages.value.push({ sender: 'user', content: userInput.value });
  if(sendMessageType.value === '1') {
    fetchData(userInput.value);
  }else {
    queryImage(userInput.value);
  }
  userInput.value = '';
};

const changeSendType = () => {
  sendMessageType.value = sendMessageType.value === '1' ? '2' : '1'
}

</script>

<template>
  <div class="chat-container">
    <div class="chat-body">
      <div v-for="(message, index) in messages" :key="index" class="message" :class="message.sender">
        <img v-if="message.type === 'image'" :src="message.content || 'https://img1.baidu.com/it/u=2057385653,3683711847&fm=253&fmt=auto&app=138&f=GIF?w=285&h=285'"/>
        <div v-else class="message-content" v-html="message.content">
        </div>
      </div>
    </div>
    <div class="input-area">
      <button @click="changeSendType">{{ sendMessageType == '1' ? '文本模型' : '图片模型' }}</button>
      <input v-model="userInput" @keyup.enter="sendMessage" placeholder="Type a message..." />
      <button @click="sendMessage">发送</button>
    </div>
  </div>
</template>

<style scoped>
.chat-container {
  border: 1px solid #ddd;
  border-radius: 8px;
  background-color: #f9f9f9;
  display: flex;
  flex-direction: column;
  height: 100vh;
  /* 调整高度以适应输入区域 */
  width: 100vw;
  overflow-y: auto;
  /* 添加滚动条 */
}

.message {
  margin-bottom: 10px;
  padding: 5px;
  border-radius: 5px;
  max-width: 70%;
  word-wrap: break-word;
}

.chat-body {
  width: 100%;
  box-sizing: border-box;
  padding: 20px 8vw 60px 8vw;
}

img {
  width: 125px;
  height: 125px;
}

.message.user {
  align-self: flex-end;
  margin-left: 30%;
  display: flex;
  justify-content: flex-end;
}

.message.bot {
  align-self: flex-start;
  display: flex;
  max-width: 100%;
  justify-content: flex-start;
}

.message-content {
  white-space: pre-wrap;
  text-align: left;
  font-size: 12px;
}

.input-area {
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
  padding: 10px;
  border-top: 1px solid #ddd;
  background-color: #fff;
  position: fixed;
  bottom: 0;
  width: 100%;
  height: 60px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
}
button {
  font-size: 10px;
}

.input-area input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
  margin: 0 10px;
  background-color: #fff;
  color: #333;
  /* 深灰色 */
}

.input-area button {
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  background-color: #ddd;
  color: #333;
  /* 深灰色 */
  cursor: pointer;
}

.input-area button:hover {
  background-color: #ccc;
}

.message.user .message-content {
  background-color: #e6f7ff;
  padding: 5px 10px;
  border-radius: 15px;
}

.message.bot .message-content {
  background-color: #f0f0f0;
  padding: 10px;
  border-radius: 15px 15px 15px 15px;
}
</style>